package auto.app.util;

import auto.app.config.OSSProperties;
import auto.app.model.AutoFileInfo;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

@Component
public class OSSTemplate {
    @Resource
    private OSSProperties ossProperties;

    private OSSClientBuilder ossClientBuilder = new OSSClientBuilder();

    public AutoFileInfo uploadFile(String buckeName, String name, InputStream file){
        //获取时间
        Date thisDate = new Date();
        SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd");
        String format = f.format(thisDate);
        //文件上传服务器地址
        String fileName=format+"/"+name;
        OSS oss=null;
        try {
            oss=ossClientBuilder.build(ossProperties.getEndpoint(),ossProperties.getAccessId(),ossProperties.getAccessKey());
            PutObjectResult putObjectResult = oss.putObject(buckeName,fileName, file);
            return AutoFileInfo.builder().id(IdUtil.simpleUUID()).bucketName(buckeName).originalFileName(name).fileName(fileName).createTime(LocalDateTime.now()).build();
        }finally {
            if (oss!=null)oss.shutdown();
        }
    }
    public AutoFileInfo uploadFile(String name, InputStream file){
        return uploadFile(ossProperties.getBuckeName(),name,file);
    }

    public void removeFile(String buckeName, String name){
        OSS oss=null;
        try {
            oss=ossClientBuilder.build(ossProperties.getEndpoint(),ossProperties.getAccessId(),ossProperties.getAccessKey());
            oss.deleteObject(buckeName,name);
        }finally {
            if (oss!=null)oss.shutdown();
        }
    }

    /**
     *
     * @param name 文件名
     * @return  oss外网url
     */
    public String downloadFile(String name){
        OSS oss=null;
        try {
            oss=ossClientBuilder.build(ossProperties.getEndpoint(),ossProperties.getAccessId(),ossProperties.getAccessKey());
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            String url = oss.generatePresignedUrl(ossProperties.getBuckeName(), name, expiration).toString();
            return url;
        }finally {
            if (oss!=null)oss.shutdown();
        }
    }

    /**
     *
     * @param name 文件路径
     * @param oldname 文件原名
     * @param response
     */
    public void downloadFile(String name, String oldname,HttpServletResponse response){
        OSS oss=null;
        try {
            oss=ossClientBuilder.build(ossProperties.getEndpoint(),ossProperties.getAccessId(),ossProperties.getAccessKey());
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            String url = oss.generatePresignedUrl(ossProperties.getBuckeName(), name, expiration).toString();
            byte[] bytes = FilesUtil.downFileByUrl(url);
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            byteArrayOutputStream.write(bytes);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(oldname, "UTF-8"));
            response.setContentType("application/pdf");
            response.setContentLength(byteArrayOutputStream.size());
            ServletOutputStream outputStream = response.getOutputStream();
            //上传OSS文件
            byteArrayOutputStream.writeTo(outputStream);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oss!=null)oss.shutdown();
        }
    }

}
